package com.dotstone.chipism.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.adapter.ShareAdapter;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.bean.Share;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.listener.UpdateDataListener;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.MsgCode;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.util.Util;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShareManagerActivity extends BaseActivity {
	private LinearLayout mBackL;
	private TextView mStatusBar;
	private ListView mShareLv;
	private ShareAdapter mAdapter;
	private List<Share> mShares = new ArrayList<Share>();
	private NormalDialog mNormalDialog;
	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;
	private SVProgressHUD mSVProgressBar;

	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back_layout:
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void initParms(Bundle parms) {
		// TODO Auto-generated method stub

	}

	@Override
	public View bindView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int bindLayout() {
		// TODO Auto-generated method stub
		return R.layout.activity_share_manager1;
	}

	@Override
	public void initView(View view) {
		// TODO Auto-generated method stub
		mBackL = $(R.id.back_layout);
		mStatusBar = $(R.id.tv_statusBar_mian);
		mShareLv = $(R.id.share_lv);
		mSVProgressBar = new SVProgressHUD(ShareManagerActivity.this);
		boolVersion();
		mBackL.setOnClickListener(this);
		getAllShares();
		mShareLv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// TODO Auto-generated method stub
				ToastShow.Show(getApplicationContext(),
						mShares.get(position).getName() + " " + mShares.get(position).getTime());
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		SocketManager.getInstance().setOnUpdateDataListener(new UpdateDataListener() {

			@Override
			public void onUpdate() {
				// TODO Auto-generated method stub
				getAllShares();
			}
		});
	}

	private void initData() {
		mAdapter = new ShareAdapter(getApplicationContext(), mShares);
		mAdapter.setHandler(mHandler);
		mShareLv.setAdapter(mAdapter);
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if(mSVProgressBar.isShowing()){
					mSVProgressBar.dismiss();
				}
				initData();
				break;
			case MsgCode.CODE_REMOVE_SHARE:
				int position = msg.arg1;
				removeShare(position);
				break;
			default:
				break;
			}
		}
	};

	private void removeShare(final int position) {
		mNormalDialog = new NormalDialog(ShareManagerActivity.this);
		mNormalDialog.content("是否删除该分享？").style(NormalDialog.STYLE_TWO)//
				.titleTextSize(18)//
				.showAnim(bas_in)//
				.dismissAnim(bas_out)//
				.show();
		mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
			}
		}, new OnBtnClickL() {
			@Override
			public void onBtnClick() {
				mNormalDialog.dismiss();
				if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
					ToastShow.Show(getApplicationContext(), "没有网络");
					return;
				}
				mSVProgressBar.showWithStatus("正在删除");
				RequestParams params = new RequestParams(HttpURL.HANDLE_SHARE_URL);
				params.setAsJsonContent(true);
				JSONObject obj = new JSONObject();
				try {
					obj.put("handelType", 9);
					obj.put("hid", mShares.get(position).getHid());
					obj.put("shareInfoId",mShares.get(position).getShareInfoId());
					obj.put("userId", mShares.get(position).getShareUser());
					obj.put("key", "10000");
					obj.put("requestTime", "" + System.currentTimeMillis());
					obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
					Log.i("wmy", "delete share " + obj.toString());
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
				params.setBodyContent(obj.toString());
				x.http().post(params, new Callback.CommonCallback<String>() {
					@Override
					public void onSuccess(String result) {
						Log.i("wmy", "delete =" + result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String resultCode = jsonObject.getString("resultCode");
							if (resultCode.equals("1")) {
								ToastShow.Show(getApplicationContext(), "删除成功");
								getAllShares();
							} else {
								if(mSVProgressBar.isShowing()){
									mSVProgressBar.dismiss();
								}
								String errorMsg = jsonObject.optString("errorMsg");
								ToastShow.Show(getApplicationContext(), "删除失败："+errorMsg);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onCancelled(CancelledException arg0) {

					}

					@Override
					public void onError(Throwable arg0, boolean arg1) {

					}

					@Override
					public void onFinished() {

					}
				});

			}
		});
	}

	private void getAllShares() {
		if (NetUtil.isNetworkAvailable(getApplicationContext())) {
			if (!Util.isLogin(getApplicationContext())) {
				return;
			}
			RequestParams params = new RequestParams(HttpURL.GET_SHARE_HISTORY_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			try {
				obj.put("key", "10000");
				obj.put("requestTime", "" + System.currentTimeMillis());
				obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
				Log.d("test", " get all obj = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());
			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("wmy", "get all share =" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);
						String resultCode = jsonObject.getString("resultCode");
						if (resultCode.equals("1")) {
							mShares.clear();
							JSONArray data = jsonObject.getJSONArray("data");
							Log.e("wmy", "length " + data.length());
							if (data.length() != 0) {
								for (int i = 0; i < data.length(); i++) {
									JSONObject jo = data.getJSONObject(i);
									String shareId = jo.getString("shareId");
									String shareInfoId = jo.getString("shareInfoId");
									String createUser = jo.getString("createUser");
									String shareUser = jo.getString("shareUser");
									String shareRemarks = jo.getString("shareRemarks");
									long createTime = jo.getLong("createTime");
									String shareMobile = jo.getString("shareMobile");
									String hid = jo.getString("hid");
									Share s = new Share(shareId, createUser,shareInfoId, shareUser, shareRemarks, createTime,
											shareMobile, hid);
									mShares.add(s);
								}
							}
							Message msg = Message.obtain();
							msg.what = 0;
							mHandler.sendMessage(msg);

						} else if (resultCode.equals("10003")) {
							// 在这里判断token有效性
							if(mSVProgressBar.isShowing()){
								mSVProgressBar.dismiss();
							}
							Toast.makeText(getApplicationContext(), "您的登陆已超时，请重新登陆", Toast.LENGTH_SHORT).show();
							startActivity(new Intent(getApplicationContext(), LoginActivity.class));
							finish();
						}else{
							if(mSVProgressBar.isShowing()){
								mSVProgressBar.dismiss();
							}
							String errorMsg = jsonObject.getString("errorMsg");
							ToastShow.Show(getApplicationContext(), "获取分享失败"+errorMsg);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onCancelled(CancelledException arg0) {
				}

				@Override
				public void onError(Throwable arg0, boolean arg1) {
					// lt.error();
				}

				@Override
				public void onFinished() {
				}
			});
		}
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			mStatusBar.setLayoutParams(layoutParams1);
			mStatusBar.setVisibility(View.VISIBLE);
		} else {
			mStatusBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void setListener() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doBusiness(Context mContext) {
		// TODO Auto-generated method stub

	}

}
